class QiniuController < ApplicationController

  def up_token
    #生成七牛所需的uptoken 供前端使用
    return_body = %Q({"key":$(key),"hash":$(hash),"persistent_id":$(persistentId)})

    persistent_options = %w(avthumb/mp4/vb/1400k/vcodec/libx264/acodec/libfaac/s/1024x768/autoscale/1)
    # 转码完成后的回调地址  TODO 写入配置文件
    persistent_notify_url = "http://lucksh.com/qiniu/qiniu_persistent_result"
    uptoken = Qiniu.generate_upload_token(:scope => 'luke', 
      return_body: return_body,
      deadline: (Time.now + 30.seconds).to_i,
      :expires_in => 2400,
      persistent_ops: persistent_options.join(';'),
      persistent_notify_url: persistent_notify_url)
    render json: { uptoken: uptoken }
  end


def qiniu_persistent_result
    #  0 表示成功，1 表示等待处理，2 表示正在处理，3 表示处理失败，4 表示回调失败。
    puts "-----------------------------------------------------------------------------------------------------------------------"
    persistent_id = params[:id]

    media = Doing.where(persistent_id: params[:id]).first

    code = params[:code].to_i
    if code == 0
      path = Hash.new
      items = params[:items]
      items.each { |item|
        if item[:cmd] =~ %r{avthumb/mp4/vb/1400k/vcodec/libx264/acodec/libfaac/s/1024x768}
          if item[:code].to_i == 0
            path[:ipad] = item[:key]
          end
        end
      }
      media[:persistent_path] = path
      logger.info params.inspect
    else
      media[:persistent_path] = {:code => code}
    end
    media.save

    render :json => {:result => true}
  end


end